package chapter8;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet("/userloginServlet.do")
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setContentType("text/html;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		DataSource dataSource = (DataSource) getServletContext().getAttribute(
				"dataSource");
		boolean valid = false;
		try {
			Connection conn = dataSource.getConnection();
			String sql = "SELECT * FROM userinfo WHERE username=? AND password=?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			
			ResultSet rst = pstmt.executeQuery();
			valid = rst.next();
			if (valid) {
				User validuser = new User(username, password);
				request.getSession().setAttribute("user", validuser);
				System.out.println("欢迎您, " + username);
				out.println("欢迎您, " + username);
			} else {
				response.sendRedirect("chapter7/error.jsp");
			}
		} catch (Exception e) {
			log("产生异常：" + e.getMessage());
		}
	}
}
